<template>
  <div class="coincertificate-list">
    <Row type="flex" justify="space-between" class="coincertificate-list-edit">
      <Col span="8">
        <Row type="flex" justify="start">
          <Col>
            <RadioGroup
              v-model="bottonActive"
              @on-change="handleRadio"

              class="from"
              type="button"
              size="large"
            >
              <Radio :class="{ activeRadio: bottonActive === '兑换券统计' }" label="兑换券统计"></Radio>
              <Radio :class="{ activeRadio: bottonActive === '套餐统计' }" label="套餐统计"></Radio>
            </RadioGroup>
          </Col>
        </Row>
      </Col>
      <Col span="16">
        <Row type="flex" justify="end" class="code-row-bg">
          <Col>
            <Form class="from" :model="searchObj" label-position="left" inline>
              <FormItem :label-width="48">
                <div slot="label" style="transform: translateX(12px);">时间：</div>
                <RadioGroup
                  style="margin-right: 10px"
                  @on-change="search"
                  v-model="bottonDateActive"
                  type="button"
                >
                  <Radio label="日"></Radio>
                  <Radio label="月"></Radio>
                </RadioGroup>
                <DatePicker
                  v-show="dateType === 'date'"
                  type="daterange"
                  placeholder="请选择时间"
                  placement="bottom"
                  :options="dateOption"
                  :editable="false"
                  @on-change="search"
                  v-model="searchObj.dateRange"
                  :format="dateFormat"
                  class="data-time-style"
                  style="width:180px;"
                ></DatePicker>
                <DatePicker
                  v-show="dateType === 'month'"
                  :type="dateType"
                  placeholder="请选择时间"
                  placement="bottom"
                  :options="dateOption"
                  :editable="false"
                  @on-change="search"
                  v-model="searchObj.dateTimes"
                  :format="dateFormat"
                  class="data-time-style"
                  style="width:180px;"
                ></DatePicker>
              </FormItem>
              <FormItem :label-width="72">
                <div slot="label" style="transform: translateX(12px);">门店名称：</div>
                <!-- <Select
                  class="select-shop-item"
                  v-model="searchObj.shopIds"
                  multiple
                  filterable
                  @on-change="search"
                  :max-tag-count="1"
                  :max-tag-placeholder="maxTagPlaceholder"
                  style="width:180px"
                >
                  <Option
                    v-for="item in shopList"
                    :value="item.shopId"
                    :key="item.shopId"
                  >{{ item.shopName }}</Option>
                </Select>-->

                <treeselect
                  v-model="searchObj.newShopIds"
                  :multiple="true"
                  :clearable="true"
                  style="width:180px;"
                  :options="treeselectoptions"
                  :default-expand-level="1"

                  :limit="1"
                  @input="handletreeChange"
                  :normalizer="treeselectnormalizer"
                  :limitText="limitText"
                  search-nested
                  placeholder="请选择"
                >
                  <div
                    slot="value-label"
                    class="treeselect-item"
                    slot-scope="{ node }"
                  >{{ node.raw.orgName}}</div>
                </treeselect>
              </FormItem>

              <FormItem>
                <Button type="primary" class="coinrevenue-btn" @click="search">查询</Button>
              </FormItem>
            </Form>
          </Col>
        </Row>
      </Col>
    </Row>

    <div class="gamecurrencyTable">
      <div class="gamecurrencyTable-cont">
        <el-table
          v-show="bottonActive === '兑换券统计'"
          :summary-method="getSummaries"
          show-summary
          :row-class-name="tableRowClassName"
          :header-row-class-name="tableHeaderRowClassName"
          :header-cell-class-name="tableHeaderCellClassName"
          :data="resData"
          style="width: 100%;margin-bottom: 20px;border: 1px solid #dcdee2;"
          row-key="rowKey"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column prop="couponName" label="兑换券名称" width="250">
            <template slot-scope="scope">
              <!-- <div> -->
              <!-- <span>{{scope.row}}</span> -->
              <span>{{scope.row.couponName}}</span>
              <!-- v-if="scope.row.pkgStatus === 2" -->
              <span v-if="scope.row.pkgStatus === 2" class="table-delete">删除</span>
              <!-- </div> -->
            </template>
          </el-table-column>

          <el-table-column prop="convertCount" label="兑换券张数" width="180">
            <template slot-scope="scope">
              <!-- <span>{{scope.row}}</span>
              <span>test</span>-->
              <div
                :disabled="!scope.row.couponId"
                :class="{ 'table-link': scope.row.couponId }"
                class="table-link-button"
                @click="handleGoDetai(scope.row, scope.columnIndex, scope)"
              >
                <span class="convertCount">{{scope.row.convertCount}}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="convertCoinNum" label="兑换游戏币数"></el-table-column>
          <el-table-column prop="convertCoinTotalNum" label="金额"></el-table-column>
        </el-table>

        <el-table
          v-show="bottonActive === '套餐统计'"
          :summary-method="getSummaries"
          show-summary
          :data="comboData"
          :row-class-name="tableRowClassName"
          :header-row-class-name="tableHeaderRowClassName"
          :header-cell-class-name="tableHeaderCellClassName"
          style="width: 100%;margin-bottom: 20px;border: 1px solid #dcdee2"
          row-key="rowKey"
          default-expand-all
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
        >
          <el-table-column prop="pkgName" label="套餐名称" width="250">
            <template slot-scope="scope">
              <!-- <div> -->
              <!-- <span>{{scope.row}}</span> -->
              <span>{{scope.row.pkgName}}</span>
              <!-- v-if="scope.row.pkgStatus === 2" -->
              <span v-if="scope.row.pkgStatus === 2" class="table-delete">删除</span>
              <!-- </div> -->
            </template>
          </el-table-column>
          <el-table-column prop="pkgSalesCount" label="消费数量" width="180"></el-table-column>
          <el-table-column prop="pkgSalesCoinNum" label="购币总数">
            <template slot-scope="scope">
              <div
                :disabled="!scope.row.pkgId"
                :class="{ 'table-link': scope.row.pkgId }"
                class="table-link-button"
                @click="handleGoDetai(scope.row, scope.columnIndex, scope)"
              >
                <span class="convertCount">{{scope.row.pkgSalesCoinNum}}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="pkgGiveCoinNum" label="赠币总数"></el-table-column>
          <el-table-column prop="pkgSalesMoney" label="消费总额"></el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
// import { rowSpanTable, formatRowspanData } from '@/libs/rowspan'
import { shopCoincertificateQuery, shopcoincertificatePkg } from '@/api/report/shop'
import errorCaptured from '@/libs/errorCaptured'

import { getShopList } from '@/api/system/store'
import dayjs from 'dayjs'
import { getOrgAllTree } from '@/api/system/org'
import { Table, TableColumn } from 'element-ui'
import { Decimal } from 'decimal.js'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'report_shop_coincertificate',
  components: { ElTable: Table, ElTableColumn: TableColumn, Treeselect },
  data () {
    return {
      shopList: [],
      total: 0,
      isloading: false,
      bottonActive: '兑换券统计',
      bottonDateActive: '日',
      treeselectoptions: [],
      searchObj: {
        dateTimes: new Date(),
        dateRange: [new Date(), new Date()],
        pageSize: 10,
        shopIds: [],
        newShopIds: []
      },
      dateOption: {
        disabledDate (date) {
          return dayjs(date).isAfter(dayjs(new Date()))
        }
      },
      data2: [],
      columns2: [
        {
          label: '兑换券名称',
          prop: 'couponName',
          minWidth: '200px',
          align: 'left',
          headerAlign: 'left',
          footerAlige: 'left'
        },
        {
          label: '兑换券张数',
          prop: 'convertCount',
          type: 'template',
          template: 'convertCount',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '兑换游戏币数',
          prop: 'convertCoinNum',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '金额',
          prop: 'convertCoinTotalNum',
          align: 'left',
          headerAlign: 'left'
          // type: 'template',
          // template: 'withdrawNum'
        }
      ],
      columns3: [
        {
          label: '套餐名称',
          prop: 'pkgName',
          type: 'template',
          template: 'pkgName',
          minWidth: '200px',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '消费数量',
          prop: 'pkgSalesCount',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '购币总数',
          prop: 'pkgSalesCoinNum',
          type: 'template',
          template: 'pkgSalesCoinNum',
          align: 'left',
          headerAlign: 'left'
        },
        {
          label: '赠币总数',
          prop: 'pkgGiveCoinNum',
          align: 'left',
          headerAlign: 'left'
          // type: 'template',
          // template: 'pkgGiveCoinNum'
        },
        {
          label: '消费总额',
          prop: 'pkgSalesMoney',
          align: 'left',
          headerAlign: 'left'
          // type: 'template',
          // template: 'pkgSalesMoney'
        }
      ],

      resData: [], // 兑换券统计
      comboData: [] // 套餐统计
    }
  },
  computed: {
    tableCulumns () {
      if (this.bottonActive === '兑换券统计') return this.columns2
      return this.columns3
    },
    dateFormat () {
      if (this.bottonDateActive === '日') return 'yyyy-MM-dd'
      return 'yyyy-MM'
    },
    dateType () {
      if (this.bottonDateActive === '日') return 'date'
      return 'month'
    },
    startDate () {
      if (this.bottonDateActive === '日') {
        return dayjs(this.searchObj.dateRange[0]).format('YYYY-MM-DD 00:00:00')
      }
      return dayjs(this.searchObj.dateTimes).format('YYYY-MM-01 00:00:00')
    },
    endDate () {
      if (this.bottonDateActive === '日') {
        return dayjs(this.searchObj.dateRange[1])
          .add(1, 'day')
          .format('YYYY-MM-DD 00:00:00')
      }
      return dayjs(this.searchObj.dateTimes)
        .add(1, 'month')
        .format('YYYY-MM-01 00:00:00')
    }
  },
  watch: {
    'searchObj.shopIds': {
      deep: true,
      immediate: true,
      handler: function (value) {
        // debugger

        // console.log(value)
      }
    }
  },
  async created () {
    // 'e12ecec4-1ebb-4786-ad15-21e98604b966' ||
    this.searchObj.newShopIds.push(this.$store.state.user.orgId)
    this.getShopList()
    this.shopCoincertificateQuery()
    this.getOrgAllTree()
  },
  mounted () {
    // this.getShopList()
  },
  methods: {
    maxTagPlaceholder (num) {
      return '...'
    },
    limitText () {
      return '...'
    },
    // 改变门店
    handletreeChange (searchQuery, instanceId) {
      // console.log(searchQuery)
      // console.log(instanceId)
      this.flitterShopID(this.treeselectoptions)
    },
    flitterShopID (arr) {
      let shopList = arr.map(item => {
        // 如果选中的数组织
        console.log(this.searchObj.newShopIds.includes(item.id))
        if (this.searchObj.newShopIds.includes(item.id) && item.orgType === 0 && item.childList && item.childList.length) {
          return this.flitterShopIDItem(item.childList)
        } else if (this.searchObj.newShopIds.includes(item.id) && item.orgType === 1) { // 如果选中的是门店
          return item.id
        } else {
          return this.flitterShopID(item.childList)
        }
      })
      this.searchObj.shopIds = shopList.flat(Infinity)
      console.log()
    },
    // 过滤选中的组织
    flitterShopIDItem (arr) {
      return arr.map(item => {
        if (item.orgType === 0 && item.childList && item.childList.length) {
          return this.flitterShopIDItem(item.childList)
        }
        return item.id
      })
    },
    treeselectnormalizer (node) {
      return {
        id: node.id,
        label: node.orgName,
        children: node.childList && node.childList.length ? node.childList : undefined
      }
    },
    async getOrgAllTree () {
      const [err, res] = await errorCaptured(getOrgAllTree, {
        merchantId: this.$store.state.user.merchantId,
        orgType: 1
      })
      if (err) return null
      this.treeselectoptions = [res.data.data]
      this.flitterShopID(this.treeselectoptions)
    },
    // 总计
    getSummaries (param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
          sums[index] += ''
        } else {
          sums[index] = 'N/A'
        }
      })
      return sums
    },
    // 添加表格class
    tableRowClassName ({ row, rowIndex }) {
      if (rowIndex % 2 === 1) {
        return 'table-row-color'
      }
      return ''
    },
    // 设置表格头部class
    tableHeaderRowClassName ({ row, rowIndex }) {
      console.log(row, rowIndex)
      return 'gray-header'
    },
    // 表头单元格样式
    tableHeaderCellClassName ({ row, rowIndex }) {
      return 'gray-header'
    },
    async getShopList () {
      let params = {
        permissionCode: 'moms:report:coincouponanalytics', // 查看普通订单
        merchantId: this.$store.state.user.merchantId, // 商户id
        offset: 0,
        limit: 9999
      }
      let [err, shopList] = await errorCaptured(getShopList, params)

      if (err) return null
      if (shopList.data.status !== 200) return this.$Message.error(`${shopList.data.error}`)
      this.shopList = shopList.data.data || []
    },
    handleGoDetai (val, index, scope) {
      //  debugger

      if (!val.couponId && !val.pkgId) return
      let shopId = val.shopId

      this.$router.push({
        name: 'report_shop_coincertificate_detail',
        params: {
          id: val.couponId || val.pkgId,
          title: this.bottonActive,
          startDate: this.startDate,
          endDate: this.endDate,
          shopId
        }
      })
    },
    handleRadio (value) {
      if (value === '兑换券统计') return this.shopCoincertificateQuery()
      this.shopcoincertificatePkg()
    },
    // 兑换券统计查询
    async shopCoincertificateQuery () {
      this.isloading = true
      let params = {
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopIds,
        startDate: this.startDate,
        endDate: this.endDate
        // shopIds: ['e12ecec4-1ebb-4786-ad15-21e98604b966']
        // startDate: '2019-07-08',
        // endDate: '2019-07-09'
      }
      const [err, res] = await errorCaptured(shopCoincertificateQuery, params)

      this.isloading = false
      if (err) return null
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`) && (this.resData = [])

      let keys = this.columns2.map(item => item.prop)

      let data = (res.data.data || []).map((item, index) => {
        item.couponName = item.shopName
        item.children = item.coupons
        item.rowKey = index + 1
        item.coupons &&
          item.coupons.forEach((element, k) => {
            element.rowKey = Number(String(index + 1) + String(k + 1))
            element.shopId = item.shopId
            Object.keys(element).forEach(key => {
              if (keys.includes(key)) {
                if (key === 'couponName') {
                  item[key] = item.shopName
                } else {
                  item[key] = new Decimal(item[key] ? item[key] : 0).add(element[key] ? element[key] : 0).valueOf()
                }
              }
            })
          })
        return item
      })

      this.resData = data
    },
    // shopcoincertificatePkg 套餐统计查询
    async shopcoincertificatePkg (
      params = {
        merchantId: this.$store.state.user.merchantId,
        shopIds: this.searchObj.shopIds,
        startDate: this.startDate,
        endDate: this.endDate

        // 'shopIds': ['e12ecec4-1ebb-4786-ad15-21e98604b966']
      }
    ) {
      this.isloading = true

      // try {
      const [err, res] = await errorCaptured(shopcoincertificatePkg, params)
      if (err) return null
      // const res = await shopcoincertificatePkg(params)

      this.isloading = false
      if (res.data.status !== 200) return this.$Message.error(`${res.data.error}`)

      let keys = this.columns3.map(list => {
        return list.prop
      })

      this.comboData = (res.data.data || []).map((item, index) => {
        item.children = item.pkgs
        item.pkgName = item.shopName
        item.rowKey = index + 1
        // debugger
        // keys.map(keyItem => {
        //     item[keyItem] = 0
        // })
        item.pkgs &&
          item.pkgs.forEach((element, k) => {
            element.shopId = item.shopId
            element.rowKey = Number(String(index + 1) + String(k + 1))
            // element
            // element.pkgName = item.shopName
            Object.keys(element).forEach(key => {
              if (keys.includes(key)) {
                if (key === 'pkgName') {
                  item[key] = item.shopName
                } else {
                  item[key] = new Decimal(item[key] ? item[key] : 0).add(element[key]).valueOf()
                }
              }
            })
          })

        return item
      })

      // this.resData = [Object.assign({}, { shopName: data.shopName }, obj)]
      // } catch (error) {
      //   this.isloading = false
      //   this.$Message.error(`${error}`)
      // }
    },
    search () {
      if (this.bottonActive === '兑换券统计') return this.shopCoincertificateQuery()
      this.shopcoincertificatePkg()
      // this.shopCoincertificateQuery()
    }
  }
}
</script>
<style lang="less" scoped>
.coincertificate-list {
  min-width: 1015px;
  .from {
    margin-top: 24px;
  }
  .bottonActive{
   background: #2D8CF0;
  }
  .ivu-radio-group-button .ivu-radio-wrapper-checked{
    background: #2D8CF0;
    color: #fff;
  }
  .table-delete {
    padding: 5px;
    border-radius: 2px;
    background: #ed4014;
    font-size: 10px;
    color: #ffffff;
    letter-spacing: 0;
    text-align: justify;
  }
  .table-link-button {
    border: none;
    background: none;
    // color: #2d8cf0;
  }
  .table-link {
    width: 100%;
    height: 100%;
    font-size: 12px;
    letter-spacing: 0;
    span {
      color: #464c5b;
      border-bottom: 1px solid #fff;
      border-bottom-width: 0;
      color: #2d8cf0;
      cursor: pointer;
      color: #2d8cf0;
      border-bottom-width: 1px;
      border-bottom-color: #2d8cf0;
    }
  }
  .coincertificate-list-edit {
    padding-left: 20px;
  }
  .button_active {
    border: 1px solid #2d8cf0;
  }
  .gamecurrencyTable {
    background: #ffffff;
    padding: 40px 0;
    width: 100%;
    .gamecurrencyTable-cont {
      width: 70%;
      margin: auto;
    }
  }
}
</style>
<style lang="less">
.coincertificate-list {
  .select-shop-item {
    height: 35px;
    width: 210px;
    .ivu-select-selection {
      height: 35px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }

    .ivu-tag {
      max-width: 100px;
    }
  }
  .gray-header {
    background-color: #f8f8f9;
    height: 40px;
    padding: 6px 0;
    font-weight: bold;
    color: #515a6e;
  }
  .table-row-color {
    background-color: #f8f8f9;
  }

  .treeselect-item {
    max-width: 80px;

    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    height: 24px;
    line-height: 24px;
  }
  .vue-treeselect__multi-value {
    line-height: normal;
    margin-bottom: 0px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .vue-treeselect__multi-value-item-container {
    padding-top: 0px;
  }
  .vue-treeselect__multi-value-item {
    cursor: pointer;
    display: inline-table;
    background: #e3f2fd;
    padding: 0 0;
    border: 1px solid transparent;
    border-radius: 2px;
    color: #039be5;
    font-size: 12px;
    vertical-align: top;
  }
}
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
